from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from flask_wtf import CSRFProtect
from flask_migrate import Migrate
import requests
from lxml import etree
from datetime import datetime

csrf = CSRFProtect()
db = SQLAlchemy()
migrate = Migrate()


# 自定义一个filter函数处理密码
def protect(n):
    return n.replace(f'{n}', '*' * len(n))



def create_app():
    app = Flask(__name__)
    from system_manage.oa_system import oa_system
    app.register_blueprint(oa_system, url_prefix='/oa_system')
    app.config.from_object('system_manage.config.BaseConfig')
    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    app.add_template_filter(protect, 'protect')
    app.app_context().push()
    # add_news()
    return app


def add_news():
    from .models import News
    for i in range(1, 11):
        url = f'https://voice.hupu.com/news?category=all&page={i}'
        data = requests.get(url).content.decode()
        html = etree.HTML(data)
        news_list = html.xpath('/html/body/div[3]/div[1]/div[2]/ul//li')
        for h_news in news_list:
            content = h_news.xpath('./div[1]/h4/a/text()')[0].strip()
            print(content)
            author = h_news.xpath('.//span[@class="comeFrom"]/a/text()')[0].strip()
            releaseTime = h_news.xpath('.//span[@class="other-left"]/a/@title')[0]
            n = News(
                title=content,
                author=author,
                publish_time =datetime.strptime(releaseTime, '%Y-%m-%d %H:%M'),
                content=content,
                picture=None

            )
            n.add()
